const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../../common/bee/bee')

// 获取角色拥有的菜单
router.get('/getRoleMenu', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { role_id, sqltype } = req.query
  // sqltype  个位数 1=获取角色不拥有的菜单 0=获取角色拥有的菜单 十位数：0=升序 1=降序

  if (
    !Bee.StringUtils.isNotBlank(role_id) ||
    !Bee.StringUtils.isNotBlank(sqltype)
  )
    return handleError(10003, '参数错误')

  const [findRoleMenuError, RoleMenu] = await to(
    db.query(
      `SELECT * FROM menu WHERE id ${
        Bee.StringUtils.getStrLast(sqltype, 1) === '1' ? 'NOT' : ''
      } IN (SELECT
          m.id
          FROM
          menu m, role_menu rm, role r
          WHERE r.id=? AND r.id=rm.role_id AND rm.menu_id=m.id) ORDER BY sort ${
            Bee.StringUtils.getStrLast(sqltype, 2) === '0' ? 'ASC' : 'DESC'
          }`,
      [parseInt(role_id)]
    )
  )
  if (findRoleMenuError || !RoleMenu) return handleError(-1, findRoleMenuError)

  return resp.json({
    code: 0,
    msg: status_code[0],
    data: RoleMenu,
  })
})

module.exports = router
